import api from '@/api/index'
import { compressImage } from '@/common/utils'
const platform = uni.getSystemInfoSync().platform

export default {
  state: {
    hasLogin: false,
    token: '',
    userInfo: {}, // 用户登录信息(头像, 昵称, 资料认证状态)
    userBasicInfo: {}, // 用户基本信息(身份证信息, 紧急联系人, 资料认证状态)
    userIdInfo: {}, // 用户身份证认证信息
    userAddressBook: [], // 用户通讯录
    selectedContact: {}, // 用户从通讯录选中的联系人(用于填写收货人)
    emergencyContact: {}, // 用户从通讯录选中的紧急联系人(用于实名认证)
    ifHideAppByManual: false, // 是否手动隐藏app
    ifPassedLiveness: false
  },
  mutations: {
    SET_LOGIN_STATUS(state, flag) {
      state.hasLogin = flag
    },
    SET_TOKEN(state, token) {
      state.token = token
      uni.setStorageSync('ACCESS_TOKEN', token)
    },
    SET_USER_INFO(state, info) {
      state.userInfo = info
      uni.setStorageSync('USER_INFO', info)
    },
    SET_USER_ID_INFO(state, info) {
      state.userIdInfo = info
    },
    SET_USER_BASIC_INFO(state, info) {
      state.userBasicInfo = info
    },
    SET_USER_ADDRESSBOOK(state, addressBook) {
      state.userAddressBook = addressBook
    },
    SET_SELECTED_CONTACT(state, contact) {
      state.selectedContact = contact
    },
    SET_EMERGENCY_CONTACT(state, contact) {
      state.emergencyContact = contact
    },
    SET_APP_DISPLAY_STATUS(state, flag) {
      state.ifHideAppByManual = flag
    },
    SET_LIVENESS_STATUS(state, flag) {
      state.ifPassedLiveness = flag
    }
  },
  actions: {
    handleLogin({commit}, userInfo) {
      const {token} = userInfo
      commit('SET_LOGIN_STATUS', true)
      commit('SET_TOKEN', token)
      commit('SET_USER_INFO', userInfo)
    },
    handleLogout({commit}) {
      commit('SET_LOGIN_STATUS', false)
      commit('SET_TOKEN', '')
      commit('SET_USER_INFO', {})
    },
    /** 获取用户通讯录 */
    getUserAddressBook({ commit, dispatch }) {
      return new Promise(resolve => {
        // #ifdef APP-PLUS
        plus.contacts.getAddressBook(plus.contacts.ADDRESSBOOK_PHONE, addressbook => {
          // 可通过addressbook进行通讯录操作
          console.log("Get address book success!")
          addressbook.find(["displayName","phoneNumbers"], contacts => {
            let contactsList = [] // 用于保存用户通讯录
            for (let i = 0; i < contacts.length; i++) {
              if (contacts[i].displayName) { // 联系人名字不为空
                if (contacts[i].phoneNumbers.length > 0) {
                  let phoneList = [] // 联系人的所有电话号码
                  let emailList = [] // 联系人的所有邮箱
                  contacts[i].phoneNumbers.forEach(phone => {
                    phoneList.push(phone.value)
                  })
                  if (contacts[i].emails && contacts[i].emails.length > 0) { // 联系人有记录邮箱地址
                    contacts[i].emails.forEach(em => {
                      emailList.push(em.value)
                    })
                  }
                  const single = {
                    name: contacts[i].displayName,
                    phone: contacts[i].phoneNumbers[0].value,
                    phoneNumber: phoneList.join(','),
                    email: emailList.join(','),
                    phoneList
                  }
                  contactsList.push(single)
                }
              }
            }
            commit('SET_USER_ADDRESSBOOK', contactsList)
            // dispatch('saveUserAddressBook')
            resolve(contactsList)
          }, () => {
            dispatch('onAddressBookSetting')
          }, { multiple:true })
        }, e => {
          dispatch('onAddressBookSetting')
        })
        // #endif
      })
    },
    /** 权限设置 */
    onAddressBookSetting({commit}) {
      uni.showModal({
        title: '提示',
        content: 'APP通讯录权限没有开启，是否开启？',
        success(res) {
          if (res.confirm) {
            if (platform == 'ios') {
              var UIApplication = plus.ios.import("UIApplication");
              var NSURL2 = plus.ios.import("NSURL");
              var setting2 = NSURL2.URLWithString("app-settings:");
              var application2 = UIApplication.sharedApplication();
              application2.openURL(setting2);
              plus.ios.deleteObject(setting2);
              plus.ios.deleteObject(NSURL2);
              plus.ios.deleteObject(application2);
            } else {
              var main = plus.android.runtimeMainActivity();
              var bulid = plus.android.importClass("android.os.Build");
              var Intent = plus.android.importClass('android.content.Intent');
              if (bulid.VERSION.SDK_INT >= 9) {
                var intent = new Intent('android.settings.APPLICATION_DETAILS_SETTINGS');
                var Uri = plus.android.importClass('android.net.Uri');
                var uri = Uri.fromParts("package", main.getPackageName(), null)
                intent.setData(uri);
                intent.putExtra('android.content.Intent.setFlags', Intent.FLAG_ACTIVITY_NEW_TASK);
              } else if (bulid.VERSION.SDK_INT <= 8) {
                var intent = new Intent(Intent.ACTION_VIEW);
                intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                intent.putExtra("com.android.settings.ApplicationPkgName", main.getPackageName());
                intent.putExtra('android.content.Intent.setFlags', Intent.FLAG_ACTIVITY_NEW_TASK);
              }
              main.startActivity(intent)
            }
          } else {
            uni.navigateBack({
              delta: 1
            })
          }
        }
      })
    },
    /** 保存用户通讯录 */
    async saveUserAddressBook({state, dispatch}) {
      await dispatch('getUserAddressBook')
      const equipserial = await dispatch('getDeviceInfo')
      const params = {
        equipserial,
        jsondata: JSON.stringify(state.userAddressBook)
      }
      console.log('保存用户通讯录', params)
      return new Promise(resolve => {
        api.saveUserAddressBook(params).then(res => {
          console.log('保存通讯录', res)
          resolve()
          // if (!res) return
        })
      })
    },
    // 获取设备信息
    getDeviceInfo() {
      return new Promise(resolve => {
        plus.device.getInfo({
          success:function(e){
            const serial = e.uuid
            console.log('getDeviceInfo', e)
            console.log('serial', serial)
            resolve(serial)
          },
          fail:function(e){
            new Error(e)
          }
        })
      })
    },
    /** 打开相机, 拍照返回照片路径 */
    captureImage({ commit }) {
      return new Promise(resolve => {
        // 设置手动隐藏app, 用于判断是否需要做版本检查
        commit('SET_APP_DISPLAY_STATUS', true)
        const cmr = plus.camera.getCamera()
        const res = cmr.supportedImageResolutions[0]
        const fmt = cmr.supportedImageFormats[0]
        console.log("分辨率: "+res+", 格式: "+fmt)
        cmr.captureImage(async path => {
            console.log( "获取图片路径成功: " + path )
            // 压缩图片
            const afterCompress = await compressImage(path)
            resolve(afterCompress)
            commit('SET_APP_DISPLAY_STATUS', false)
          },
          error => {
            console.log( "获取图片路径失败: " + error.message )
          },
          {resolution:res, format:fmt}
        )
      })
    },
    /**
     * 从相册选择图片
     */
    chooseImageFromAlbum({}, count = 1) {
      return new Promise(resolve => {
        const defaultConfig = {
          count: count, // 选择图片的数量
          // sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sizeType: ['compressed'],
          sourceType: ['album'], // 从相册选择
          success: function (res) {
            console.log('选中图片', JSON.stringify(res))
            const { size } = res
            if (size > 1000000) { // 图片超过 1mb 则压缩
              let afterCompressArray = []
              let count = 0
              const pathsLength = res.tempFilePaths.length
              if (pathsLength !== 0) {
                res.tempFilePaths.forEach(async path => {
                  const tempPath = await compressImage(path)
                  afterCompressArray.push(tempPath)
                  count++
                  if (count === pathsLength) {
                    resolve(afterCompressArray)
                  }
                  console.log('压缩后的图片:', afterCompressArray)
                })
              }
            } else {
              resolve(res.tempFilePaths)
            }
          }
        }
        uni.chooseImage(defaultConfig)
      })
    }
  },
  getters: {}
}